package com.hcc.gateway.netty.filter;

import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.route.GatewayRoute;
import com.hcc.gateway.netty.support.GatewayConstants;

/**
 * AbstractRouteFilter
 *
 * @author shengjun.hu
 * @date 2021/12/29
 */
public abstract class AbstractMatchRouteFilter implements GatewayFilter {

    @Override
    public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
        try {
            GatewayRoute gatewayRoute = this.matchRoute(exchange);
            if (gatewayRoute == null) {
                this.matchRouteFiled(exchange);
                return;
            }

            exchange.addAttribute(GatewayConstants.GATEWAY_ROUTE_ATTR, gatewayRoute);
        } catch (Exception e) {
            this.matchRouteFiled(exchange);
        }
        chain.filter(exchange);
    }

    /**
     * 匹配路由，自行实现
     * @param exchange
     * @return
     */
    abstract public GatewayRoute matchRoute(GatewayExchange exchange);

    /**
     * 匹配路由失败
     * @param exchange
     */
    abstract public void matchRouteFiled(GatewayExchange exchange);

}
